import "dart:convert";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/mine/online_pay/api.dart";
import "package:ct_pa_majordomo/pages/mine/setting.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:flutter/material.dart";
import "package:qr_flutter/qr_flutter.dart";

class Mine extends StatefulWidget {
  const Mine({super.key});

  @override
  MineState createState() => MineState();
}

class MineState extends State<Mine> {
  Map _user = {};
  Map _paymentAccountInfo = {};

  @override
  void initState() {
    super.initState();
    _loadUserInfo();
    _getPaymentAccountInfo();
  }
  
  void _loadUserInfo() {
    String info = storage.getString("info") ?? "{}";
    if (mounted) {
      setState(() {
        _user = jsonDecode(info);
      });
    }
  }
  
  void _getPaymentAccountInfo() {
    onlinePayApi.getInfo().then((value) {
      print(":>>$value");
      setState(() {
        _paymentAccountInfo = value["data"] ?? {};
      });
    });
  }

  // 添加刷新方法，供外部调用
  void refresh() {
    _loadUserInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: Theme.of(context).copyWith(
        iconTheme: const IconThemeData(color: ThemeVars.colorPrimary, size: 28),
      ),
      child: ListView(
        padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 20) +
            MediaQuery.paddingOf(context),
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              color: ThemeVars.colorPrimary,
            ),
            child: Row(
              children: [
                GestureDetector(
                  onTap: () {
                    Stacker.pushNamed(Keys.MINE_PROFILE).then((value) {
                      refresh();
                    });
                  },
                  child: SizedBox(
                    width: 40,
                    height: 40,
                    child: _user["avatar"] != null &&
                        Utils.isNotEmpty(_user["avatar"]) &&
                        _user["avatar"].toString().startsWith("http")
                        ? ClipRRect(
                            borderRadius: BorderRadius.circular(20),
                            child: Image.network(
                              _user["avatar"],
                              fit: BoxFit.cover,
                              errorBuilder: (context, error, stackTrace) {
                                return const Icon(Icons.person,
                                    color: Colors.white, size: 40);
                              },
                            ),
                          )
                        : const Icon(Icons.person, color: Colors.white, size: 40),
                  ),
                ),
                const SizedBox(width: 10),
                DefaultTextStyle(
                  style: DefaultTextStyle.of(context).style.copyWith(
                        color: Colors.white,
                      ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        _user["nickName"] ?? "",
                        style: const TextStyle(fontWeight: FontWeight.w500),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        _user["phonenumber"] ?? "",
                        style: const TextStyle(fontSize: 12),
                      ),
                    ],
                  ),
                ),
                const Expanded(child: SizedBox()),
                IconButton(
                  icon: const Icon(Icons.settings_rounded, color: Colors.white),
                  onPressed: () { Stacker.pushNamed(Keys.MINE_SETTING); } ,
                ),
              ],
            ),
          ),
          const SizedBox(height: 15),
          MenuBlock(
            items: [
              // MenuBlockItem(
              //   prefix: const Icon(Icons.shopping_bag_outlined),
              //   text: "服务",
              // ),
              
              if (_paymentAccountInfo["auditStatus"] == null || _paymentAccountInfo["auditStatus"] != "1")
                MenuBlockItem(
                  prefix: const Icon(Icons.wallet_outlined),
                  text: "线上支付",
                  suffix: const Text(
                    "去开通",
                    style: TextStyle(color: ThemeVars.colorTextTer),
                  ),
                  onTap: () {
                    Stacker.pushNamed(Keys.ONLINE_PAY);
                  },
                ),
              if (_paymentAccountInfo["auditStatus"] != null && _paymentAccountInfo["auditStatus"] == "1")
                MenuBlockItem(
                  prefix: const Icon(Icons.wallet_outlined),
                  text: "线上支付",
                  suffix: const Text(
                    "已开通",
                    style: TextStyle(color: ThemeVars.colorTextTer),
                  ),
                  onTap: () {
                    Stacker.pushNamed(Keys.ONLINE_PAY_RECORD);
                  },
                ),
              MenuBlockItem(
                prefix: const Icon(Icons.account_balance_wallet_outlined),
                text: "提现",
                suffix: const Text(
                  "去提现",
                  style: TextStyle(color: ThemeVars.colorPrimary),
                ),
                onTap: () {
                  print(_user);
                  Stacker.pushNamed(Keys.WITHDRAW, arguments: { "apartmentId": _user["apartmentId"] });
                },
              ),
            ],
          ),
          const SizedBox(height: 15),
          MenuBlock(
            items: [
              // MenuBlockItem(
              //   prefix: const Icon(Icons.assignment_ind_rounded),
              //   text: "员工",
              // ),
              MenuBlockItem(
                prefix: const Icon(Icons.assignment_outlined),
                text: "公寓管理",
                onTap: () {
                  Stacker.pushNamed(Keys.APARTMENT_MANAGE);
                },
              ),
              MenuBlockItem(
                prefix: const Icon(Icons.assignment_outlined),
                text: "生成公寓码",
                onTap: () {
                  _showQRCode(context);
                },
              ),
            ],
          ),
          // const SizedBox(height: 15),
          // MenuBlock(
          //   items: [
          //     MenuBlockItem(
          //       prefix: const Icon(Icons.volume_up_rounded),
          //       text: "公告",
          //     ),
          //     MenuBlockItem(
          //       prefix: const Icon(Icons.list_alt_rounded),
          //       text: "日志",
          //     ),
          //     MenuBlockItem(
          //       prefix: const Icon(Icons.help_center_outlined),
          //       text: "帮助中心",
          //     ),
          //   ],
          // ),
          // const SizedBox(height: 15),
          // MenuBlock(
          //   items: [
          //     MenuBlockItem(
          //       prefix: const Icon(Icons.info_outlined),
          //       text: "关于我们",
          //     ),
          //   ],
          // ),
        ],
      ),
    );
  }
  
  void _showQRCode(BuildContext context) {
    if (_user["apartmentId"] == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('未找到公寓ID，请先设置公寓')),
      );
      return;
    }
    String qrUrl = "https://www.ctqct.net/weixin/pre-check-in?apartmentId=${_user["apartmentId"]}";
    Utils.showQRCode(context, url: qrUrl, title: "公寓二维码", tip: "扫描二维码预约入住");
  }
}
